﻿using HelperFromTheSkeleton.Common;
using HelperFromTheSkeleton.JwtHelper;
using HelperFromTheSkeleton.Model.PageModel;
using HelperFromTheSkeleton.Model.RequestModels;
using Microsoft.AspNetCore.Mvc;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace HelperFromTheSkeleton.APICore
{
    public class BaseController : ControllerBase
    {
        /// <summary>
        /// API通用处理
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        protected async Task<ResultModel> HandleAsync(Func<Task> action)
        {
            try
            {
                await action();
                return ResultModel.Succeed("成功");
            }
            catch (Exception ex)
            {
                return ResultModel.Fall(ex.Message);
            }
        }

        /// <summary>
        /// API通用处理
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        protected async Task<ResultModel<T>> HandleAsync<T>(Func<Task<T>> action)
        {
            try
            {
                var result = await action.Invoke();
                return ResultModel<T>.Succeed(result, "成功");
            }
            catch (Exception ex)
            {
                return ResultModel<T>.Fall(ex.Message);
            }
        }

        /// <summary>
        /// API通用处理
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        protected ResultModel Handle(Action action)
        {
            try
            {
                action?.Invoke();
                return ResultModel.Succeed("成功");
            }
            catch (Exception ex)
            {
                return ResultModel.Fall(ex.Message);
            }
        }

        /// <summary>
        /// API通用处理
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        protected ResultModel<T> Handle<T>(Func<T> func)
        {
            try
            {
                if (func == null) throw new InvalidOperationException("API通用处理调用的方法为空");
                var data = func.Invoke();
                return ResultModel<T>.Succeed(data, "成功");
            }
            catch (Exception ex)
            {
                return ResultModel<T>.Fall(ex.Message);
            }
        }

        /// <summary>
        /// API通用处理
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        protected async Task<PageResultModel<T>> HandleAsync<T>(Func<Task<(List<T> data, PageResultModel page)>> action)
        {
            try
            {
                var result = await action.Invoke();
                return PageResultModel<T>.Succeed(result.data, result.page, "成功");
            }
            catch (Exception ex)
            {
                return PageResultModel<T>.Fall(ex.Message);
            }
        }

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        protected string GetToken()
        {
            var authorizationList = HttpContext.Request.Headers.Authorization.ToList();
            if (authorizationList?.Count > 0)
            {
                var s = authorizationList[0]?.Split(' ');
                if (s?.Length > 1)
                {
                    return s[1];
                }
            }
            return "";
        }

        /// <summary>
        /// 获取用户ID
        /// </summary>
        /// <returns></returns>
        protected Guid? GetUserID()
        {
            object? service = base.HttpContext.RequestServices.GetService(typeof(JwtManage));
            JwtManage? jwtManage = default(JwtManage);
            int num;
            if (service != null)
            {
                jwtManage = service as JwtManage;
                num = ((jwtManage != null) ? 1 : 0);
            }
            else
            {
                num = 0;
            }

            if (num != 0)
            {
                JwtSecurityToken? jwtSecurityToken = jwtManage?.Token;
                if (jwtSecurityToken != null)
                {
                    foreach (Claim claim in jwtSecurityToken.Claims)
                    {
                        if (claim.Type == "UserID")
                        {
                            string value = claim.Value;
                            try
                            {
                                return Guid.Parse(value);
                            }
                            catch
                            {
                                return null;
                            }
                        }
                    }
                }
            }

            return null;
        }
    }
}
